<template>
    <el-card style="height: 80px;">
        <el-form :inline="true" class="form">
            <el-form-item label="用户名:">
                <el-input placeholder="请你输入搜索用户名" v-model="usernameLike"></el-input>
            </el-form-item>
            <el-form-item label="用户类型:">
                <el-select v-model="type" placeholder="请选择用户类型">
                    <el-option
                            v-for="item in options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" size="default" @click="search">搜索</el-button>
                <el-button type="primary" size="default" @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>
    <el-card style="margin: 10px 0px;">
        <el-button type="primary" size="default" @click="addUser">添加用户</el-button>
        <!-- table展示用户信息 -->
        <el-table @selection-change="selectChange" style="margin: 10px 0px;" border :data="userArr">
            <el-table-column type="selection" align="center"></el-table-column>
            <el-table-column label="#" align="center" type="index"></el-table-column>
            <el-table-column label="用户名字" align="center" prop="username" show-overflow-tooltip></el-table-column>
            <el-table-column label="用户邮箱" align="center" prop="email" show-overflow-tooltip></el-table-column>
            <el-table-column label="用户角色" align="center" prop="roleNameListStr" show-overflow-tooltip>
                <template #="{row,$index}">
                    <div v-if="row.type == 1" type="primary" plain> {{row.roleNameListStr}}</div>
                </template>
            </el-table-column>
            <el-table-column label="是否VIP" align="center" show-overflow-tooltip>
                <template #="{row,$index}">
                    <el-button v-if="row.type == 0" type="primary" plain> {{row.isVipStr}}</el-button>
                </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" show-overflow-tooltip></el-table-column>
            <el-table-column label="用户类型" align="center">
                <template #="{row,$index}">
                    <el-button type="primary" plain> {{row.typeStr}}</el-button>
                </template>
            </el-table-column>
            <el-table-column label="用户状态" align="center">
                <template #="{row,$index}">
                    <el-button :type=setStatusButton(row) plain> {{row.statusStr}}</el-button>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="300px" align="center">
                <template #="{ row, $index }">
                    <el-button v-if="row.type == 1" type="primary" size="small" icon="User" @click="setRole(row)">分配角色</el-button>
                    <el-button type="primary" size="small" icon="User" @click="closeUser(row.uuid)">
                        {{row.status=='1' ? '解冻用户' : '冻结用户'}}
                    </el-button>
                    <el-button type="primary" size="small" icon="Edit" @click="updateUser(row)">编辑</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <el-pagination v-model:current-page="page" v-model:page-size="pageSize" :page-sizes="[5, 7, 9, 11]"
            :background="true" layout="prev, pager, next, jumper,->,sizes,total" :total="items" @current-change="getHasUser"
            @size-change="handler" />
    </el-card>
    <!-- 抽屉结构:完成添加新的用户账号|更新已有的账号信息 -->
    <el-drawer v-model="drawer">
        <!-- 头部标题:将来文字内容应该动态的 -->
        <template #header>
            <h4>{{ userAddOrUpdateForm.uuid ? '更新用户' : '添加用户' }}</h4>
        </template>
        <!-- 身体部分 -->
        <template #default>
            <el-form :model="userAddOrUpdateForm" :rules="rules" ref="formRef">
                <el-form-item label="用户姓名" prop="username">
                    <el-input placeholder="请您输入用户姓名" v-model="userAddOrUpdateForm.username"></el-input>
                </el-form-item>
                <el-form-item label="用户邮箱" prop="email" v-if="!userAddOrUpdateForm.uuid">
                    <el-input placeholder="请您输入用户邮箱" v-model="userAddOrUpdateForm.email"></el-input>
                </el-form-item>
                <el-form-item label="用户密码" prop="password" v-if="!userAddOrUpdateForm.uuid">
                    <el-input placeholder="请您输入用户密码" v-model="userAddOrUpdateForm.password"></el-input>
                </el-form-item>
            </el-form>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="cancel">取消</el-button>
                <el-button type="primary" @click="save">确定</el-button>
            </div>
        </template>
    </el-drawer>
    <!-- 抽屉结构:用户某一个已有的账号进行职位分配 -->
    <el-drawer v-model="userRoleDrawer">
        <template #header>
            <h4>分配角色(职位)</h4>
        </template>
        <template #default>
            <el-form>
                <el-form-item label="用户姓名">
                    <el-input v-model="userAddOrUpdateForm.username" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="职位列表">
                    <el-checkbox @change="handleCheckAllChange" v-model="checkAll"
                        :indeterminate="isIndeterminate">全选</el-checkbox>
                    <!-- 显示职位的的复选框 -->
                    <el-checkbox-group v-model="userRole" @change="handleCheckedCitiesChange">
                        <el-checkbox v-for="(role, index) in allRole" :key="index" :label="role">
                            {{ role.roleName }}
                        </el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="userRoleDrawer = false">取消</el-button>
                <el-button type="primary" @click="confirmClick">确定</el-button>
            </div>
        </template>
    </el-drawer>
</template>
<script setup lang="ts">
    import useLayOutSettingStore from '@/store/modules/setting'
    import {nextTick, onMounted, reactive, ref} from 'vue';
    import {reqAllRole, reqUserRole} from '@/api/business/role'
    import {reqAddOrUpdateUser, reqCloseUser, reqRoleUser} from '@/api/business/user/index'
    import type {User} from '@/api/acl/user/type';
    import {ElMessage} from 'element-plus';
    import {reqUserList} from "@/api/business/user";
    import {useRouter} from 'vue-router';
    import {
        handleResponseData,
        UserInfo,
        UserInfoReponseData,
        UserListReponseData,
        UserRoleForm
    } from "@/api/business/user/type";
    import {RoleAllListReponseData, RoleInfo} from "@/api/business/role/type";
    import {HandleResponseData} from "@/api/common/type";

    let $router = useRouter();
//默认页码
let page = ref<number>(0);
//一页展示几条数据
let pageSize = ref<number>(5);
let usernameLike = ref<string>('');
let type = ref<number>(1);
//按钮颜色
let status = ref<string>("success");
//用户总个数
let items = ref<number>(0);
//存储全部用户的数组
let userArr = ref<UserInfoReponseData>([]);
//定义响应式数据控制抽屉的显示与隐藏
let drawer = ref<boolean>(false);
//控制分配角色抽屉显示与隐藏
let userRoleDrawer = ref<boolean>(false);
//存储全部职位的数据
let allRole = ref<RoleInfo>([]);
//当前用户已有的职位
let userRole = ref<RoleInfo>([]);
//收集用户信息的响应式数据
let userAddOrUpdateForm = reactive<any>({
    username: '',
    email: '',
    password: '',
    uuid:''
});
//冻结用户
let uuidFrom = reactive<any>({
    uuid:''
});

const options = [
    {
        value: 0,
        label: 'app用户',
    },
    {
        value: 1,
        label: '后台用户',
    }
]
const value = ref(0)
//获取form组件实例
let formRef = ref<any>();
//定义响应式数据:收集用户输入进来的关键字
//获取模板setting仓库
let settingStore = useLayOutSettingStore();
//组件挂载完毕
onMounted(() => {
    getHasUser();
});
//获取全部已有的用户信息
const getHasUser = async (pager = 1) => {
    //收集当前页码
    page.value = pager;
    let result: UserListReponseData = await reqUserList(page.value-1,pageSize.value,usernameLike.value,type.value);
    if (result.code == 200) {
        items.value = result.result.items;
        userArr.value = result.result.data;
    }
}
//分页器下拉菜单的自定义事件的回调
const handler = () => {
    getHasUser();
}
//添加用户按钮的回调
const addUser = () => {
    //抽屉显示出来
    drawer.value = true;
    //清空数据
    Object.assign(userAddOrUpdateForm, {
        username: '',
        email: '',
        password: '',
        uuid:''
    });
    //清除上一次的错误的提示信息
    nextTick(() => {
        formRef.value.clearValidate('username');
        formRef.value.clearValidate('email');
        formRef.value.clearValidate('password');
        formRef.value.clearValidate('uuid');
    });
}
//更新已有的用户按钮的回调
//row:即为已有用户的账号信息
const updateUser = (row: User) => {
    //抽屉显示出来
    drawer.value = true;
    //存储收集已有的账号信息
    Object.assign(userAddOrUpdateForm, row);
    //清除上一次的错误的提示信息
    nextTick(() => {
        formRef.value.clearValidate('username');
        formRef.value.clearValidate('name');
    });
}

//冻结某一个用户
const closeUser = async (row: any) => {
    uuidFrom.uuid = row;
    let result: any = await reqCloseUser(uuidFrom);
    // if (result.msg.startsWith('Token无效')){
    //     //退出登录,跳转到登录页面
    //     reqLogout();
    //     $router.push('/login')
    // }
    if (result.code == 200) {
        ElMessage({ type: 'success', message: '操作成功' });
    }else {
        ElMessage({ type: 'error', message: '操作失败'+result.msg });
    }
    await getHasUser(page.value);
}
//保存按钮的回调
const save = async () => {
    //点击保存按钮的时候,务必需要保证表单全部复合条件在去发请求
    await formRef.value.validate()
    //保存按钮:添加新的用户|更新已有的用户账号信息
    let result: HandleResponseData = await reqAddOrUpdateUser(userAddOrUpdateForm);
    //添加或者更新成功
    if (result.code == '200') {
        //关闭抽屉
        drawer.value = false;
        //提示消息
        ElMessage({ type: 'success', message: userAddOrUpdateForm.uuid ? '更新成功' : '添加成功' });
        //获取最新的全部账号的信息
        // getHasUser(userParams.id ? pageNo.value : 1);
        //浏览器自动刷新一次
        window.location.reload();
    } else {
        //关闭抽屉
        drawer.value = false;
        //提示消息
        ElMessage({ type: 'error', message: userAddOrUpdateForm.uuid ? '更新失败'+result.msg : '添加失败:'+result.msg });
    }
}
//取消按钮的回调
const cancel = () => {
    //关闭抽屉
    drawer.value = false;
}
//校验用户名字回调函数
const validatorUsername = (rule: any, value: any, callBack: any) => {
    //用户名字|昵称,长度至少五位
    if (value.trim().length >= 5) {
        callBack();
    } else {
        callBack(new Error('用户名字至少五位'))
    }
}
//校验用户名字回调函数
const validatoremail = (rule: any, value: any, callBack: any) => {
    //用户名字|昵称,长度至少五位
    if (value.trim().length >= 10) {
        callBack();
    } else {
        callBack(new Error('邮箱至少10位'))
    }
}
const validatorPassword = (rule: any, value: any, callBack: any) => {
    //用户名字|昵称,长度至少五位
    if (value.trim().length >= 6) {
        callBack();
    } else {
        callBack(new Error('用户密码至少六位'))
    }
}
//表单校验的规则对象
const rules = {
    //用户名字
    username: [{ required: true, trigger: 'blur', validator: validatorUsername }],
    //用户昵称
    email: [{ required: true, trigger: 'blur', validator: validatoremail }],
    //用户的密码
    password: [{ required: true, trigger: 'blur', validator: validatorPassword }],
}
//分配角色按钮的回调
const setRole = async (row: UserInfo) => {
    //存储已有的用户信息
    Object.assign(userAddOrUpdateForm, row);
    //获取全部的职位的数据与当前用户已有的职位的数据
    let allRoleResult: RoleAllListReponseData = await reqAllRole();
    let userRoleResult: RoleAllListReponseData = await reqUserRole(row.uuid);
    if (allRoleResult.code == '200' && userRoleResult.code == '200') {
        //存储全部的职位
        allRole.value = allRoleResult.result;
        //存储当前用户已有的职位
        userRole.value = userRoleResult.result;
        //抽屉显示出来
        userRoleDrawer.value = true;
    }

}
//按设置钮颜色
const setStatusButton = (row: any) =>{
    if (row.status =='0'){
        return 'success'
    } else {
        return 'danger'
    }
}

//收集顶部复选框全选数据
const checkAll = ref<boolean>(false);
//控制顶部全选复选框不确定的样式
const isIndeterminate = ref<boolean>(true);
//顶部的全部复选框的change事件
const handleCheckAllChange = (val: boolean) => {
    //val:true(全选)|false(没有全选)
    userRole.value = val ? allRole.value : [];
    //不确定的样式(确定样式)
    isIndeterminate.value = false
}
//顶部全部的复选框的change事件
const handleCheckedCitiesChange = (value: string[]) => {
    //顶部复选框的勾选数据
    //代表:勾选上的项目个数与全部的职位个数相等，顶部的复选框勾选上
    checkAll.value = value.length === allRole.value.length;
    //不确定的样式
    isIndeterminate.value = value.length !== allRole.value.length
}
//确定按钮的回调(分配职位)
    const confirmClick = async () => {
        //收集参数
        let data: UserRoleForm = {
            userUuid: userAddOrUpdateForm.uuid,
            roleUuidList: userRole.value.map(item => {
                return (item.uuid)
            })
        }
        //分配用户的职位
        let result: any = await reqRoleUser(data);
        if (result.code == '200') {
            //提示信息
            ElMessage({type: 'success', message: '分配职务成功'});
        } else {
            ElMessage({type: 'error', message: '分配职务失败'+result.msg});
        }
        //关闭抽屉
        userRoleDrawer.value = false;
        //获取更新完毕用户的信息,更新完毕留在当前页
        getHasUser(page.value);
    }

//搜索按钮的回调
const search = () => {
    //根据关键字获取相应的用户数据
    getHasUser();
    //清空关键字
    usernameLike.value = '';
    type.value = 1;
}
//重置按钮
const reset = () => {
    settingStore.refsh = !settingStore.refsh;
}
</script>

<style scoped>
.form {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
</style>
